package com.roamer.validator;

import com.roamer.validator.time.MatchTimeContext;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Calendar;
import java.util.TimeZone;

/**
 * 时间戳验证规则
 * <p>
 * 必须是过去的时间
 * </p>
 *
 * @author roamer
 * @version V1.0
 * @date 2019/8/26 9:53 下午
 */
public class DateTimeValidator implements ConstraintValidator<DateTime, Long> {
    private MatchTimeContext matchTimeContext;
    private DimensionType dimension;
    private TimeZone timeZone;

    /**
     * 初始化
     *
     * @param constraintAnnotation 注解对象
     */
    @Override
    public void initialize(DateTime constraintAnnotation) {
        matchTimeContext = new MatchTimeContext(constraintAnnotation.matchType());
        dimension = constraintAnnotation.dimension();
        timeZone = TimeZone.getTimeZone(constraintAnnotation.timeZone());
    }

    @Override
    public boolean isValid(Long value, ConstraintValidatorContext constraintValidatorContext) {
        if (null == value) {
            return true;
        }
        Calendar fromDate = new Calendar.Builder().setInstant(value).setTimeZone(timeZone).build();
        Calendar currentDate = Calendar.getInstance(timeZone);
        switch (dimension) {
            case year:
            case month:
                fromDate.set(Calendar.DAY_OF_MONTH, 1);
                currentDate.set(Calendar.DAY_OF_MONTH, 1);
            case day:
                fromDate.set(Calendar.HOUR_OF_DAY, 0);
                currentDate.set(Calendar.HOUR_OF_DAY, 0);
            case hour:
                fromDate.set(Calendar.MINUTE, 0);
                currentDate.set(Calendar.MINUTE, 0);
            case minute:
                fromDate.set(Calendar.SECOND, 0);
                currentDate.set(Calendar.SECOND, 0);
            case second:
                fromDate.set(Calendar.MILLISECOND, 0);
                currentDate.set(Calendar.MILLISECOND, 0);
                break;
            default:
                break;
        }
        return matchTimeContext.executeMatches(fromDate.getTimeInMillis(), currentDate.getTimeInMillis());
    }

}
